<?php

header("Content-type: text/html; charset=utf-8");

$oper = $_GET['oper'];

if (!isset($oper))
{
    die("Unknown command");
}

$admin = false;
require_once('auth_req.inc.php');

switch ($oper)
{

    case 'info':

            if (!isset($_GET['cid']))
            {
                $response->error = 'Wrong params !';
                echo json_encode($response);
                return;
            }
            
            $rs = $dbh->query('SELECT * FROM network_map WHERE c_id=' . $_GET['cid']);

            if ($rec = $rs->fetchAll(PDO::FETCH_ASSOC)) 
            {
                foreach($rec[0] as $key => $val)
                {
                    $response->$key = $val;
                }
            }
            else
            {
                $response->error = 'Controller not found';
            }

            echo json_encode($response);

        break;

    case 'mlist':

        if (!isset($_GET['type']) || !isset($_GET['imp']) || !isset($_GET['cid']))
        {
            $response->error = 'Wrong params !';
            echo json_encode($response);
            return;
        }

        $where_clause = "";
        $where_limit = 14;


        if ($_GET['type'] == 0)
        {
            $where_clause .= '(log_type=0 or (log_type=1 and c_id=' . $_GET['cid'].'))';   
        }
        elseif ($_GET['type'] == 1)
        {
            $where_clause .= 'log_type=0';
        }
        else
        {
            $where_clause .= 'log_type=1 and c_id=' . $_GET['cid'];
        }
        
        if (($_GET['imp'] >= 0) && ($_GET['imp'] <= 2))
        {
            if (!empty($where_clause))
            {
                $where_clause .= " and ";
            }

            $where_clause .= "imp = " . $_GET['imp'];
        }

        if (empty($where_clause))
        {
            $response->error = 'Wrong params !';
            echo json_encode($response);
            return;
        }
        
        $rs = $dbh->query('select * from (select * from log where '.$where_clause.' order by log_id desc limit '.$where_limit.') AS tbl order by log_id desc');

        $alldb = $rs->fetchAll(PDO::FETCH_ASSOC);
        
        $response= array();

        foreach( $alldb as $key => $val)
        {
            $val['log_msg'] = preg_replace('/\[(.*)\]/suU', '<b>$1</b>',$val['log_msg']);
            $response[$key] = $val; 
        }

        echo json_encode($response);

        break;


    case 'cmd':
        
            if (!isset($_GET['cid']))
            {
                $response->error = 'Wrong params !';
                echo json_encode($response);
                return;
            }

            $cnt = intval($_GET['cid']);
            $param = intval($_GET['param']);

            $rs = $dbh->query('SELECT online FROM network_map WHERE c_id=' . $_GET['cid'].' limit 1');

            if ($rec = $rs->fetchAll(PDO::FETCH_ASSOC)) 
            {
                if ($rec[0]['online'] != 1)
                {
                    $response->error = 'Нельзя управлять контроллером с которым нет связи !';
                    echo json_encode($response);
                    return;
                }
            }
            else
            {
                $response->error = 'Нет такого контроллера !';
                echo json_encode($response);
                return;

            }

            $rs = $dbh->query('SELECT count(*) as count FROM events WHERE act=1');

            if ($rec = $rs->fetchAll(PDO::FETCH_ASSOC)) 
            {
                if ($rec[0]['count'] != 0)
                {
                    $response->error = 'Нельзя управлять в ручную контроллером пока в системе есть активные сценарии !';
                    echo json_encode($response);
                    return;
                }
            }

            switch ($_GET['cmd'])
            {
                case 'pload':
                    $cmd = 17;  
                break;

                case 'phase':
                    $cmd = 23;  
                break;

                case 'sprog':
                    $cmd = 18;  
                break;

                case 'stime':
                    $cmd = 16;  
                break;
            }

            $sth = $dbh->prepare('insert into cmd_queue (uid, c_id, cmd, param, user) values (UUID(),:cid,:cmd, :param, :user)');

            $sth->bindParam(':cid', $cnt, PDO::PARAM_INT);
            $sth->bindParam(':cmd', $cmd, PDO::PARAM_INT);
            $sth->bindParam(':param', $param, PDO::PARAM_INT);
            $sth->bindParam(':user', $user['login']);

            if (!$sth->execute())
            {
                $response->error = 'SQL Error !';
                echo json_encode($response);
                return;
            }

            $response->status = 'Command send succeful !';
            echo json_encode($response);
            return;
    break;

    case 'script':

        if (!isset($_GET['eid']))
        {
            $response->error = 'Нет номера сценария!';
            echo json_encode($response);
            return;
        }

        $sth = $dbh->prepare('SELECT ei.*, nm.online, nm.job_mode FROM event_items ei, network_map nm WHERE nm.c_id = ei.c_id and ei.e_id=:eid');

        $sth->bindParam(':eid', intval($_GET['eid']), PDO::PARAM_INT);

        $sth->execute();

        $alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

        if (count($alldb) == 0)    
        {
            $response->error = 'Неправильный номер скрипта !';
            echo json_encode($response);
            return;
        }

        $noonline = array();
        $nolocal = array();

        $ins_query = 'insert into cmd_queue (uid, c_id, cmd, param, user) values ';
        $comma = false;

        foreach( $alldb as $key => $val)
        {
            if ($val['online'] == 0)
            {
                array_push($noonline, $val['c_id']);
            }

            if ($val['job_mode'] > 0)
            {
                array_push($nolocal, $val['c_id']);
            }

            if($comma == true)
            {
                $ins_query .= ',';
            }

            if ($val['prog'] == 9)  // ЖМ
            {
                $ins_query .= '(UUID(),'.$val['c_id'].',23,142,"'.$user['login'].'")';
            }
            elseif ($val['prog'] == 10)  // ОС
            {
                $ins_query .= '(UUID(),'.$val['c_id'].',23,143,"'.$user['login'].'")';
            }
            else
            {
                $ins_query .= '(UUID(),'.$val['c_id'].',18,'.$val['prog'].',"'.$user['login'].'")';
            }

            $comma = true;
        }

        if ((count($noonline) > 0) || (count($nolocal) > 0 ))
        {
            $msg = '';

            if (count($noonline) > 0)
            {
                $msg .= implode(',',$noonline).' отключены';
            }

            if (count($nolocal) > 0)
            {
                if (strlen($msg) > 0)
                {
                    $msg .= ' и контроллер(ы): ';
                }

                $msg .= implode(',',$nolocal).' не в локальном режиме работы';
            }

            $response->error = 'Нельзя выполнить сценарий пока контроллер(ы): '.$msg.'!';
            echo json_encode($response);
            return;
        }

        try
        {
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $dbh->beginTransaction();

            $dbh->exec($ins_query);

            $sth = $dbh->prepare('update events set act=1 where e_id=:eid');
            $sth->execute(array('eid'=>intval($_GET['eid'])));

            $sth = $dbh->prepare('insert into log (log_date,log_type, imp, user,log_msg) values (NOW(),0,0,:user,"Оператор активировал сценарий")');
            $sth->execute(array('user'=> $user['login']));

            $dbh->commit();

        } 
        catch (Exception $e)
        {
            $dbh->rollBack();
            $response->error = "Ошибка выполнения сценария !\nПовторите еще.";
            echo json_encode($response);
            return;
        }

        $response->status = 'Выполнена команда вызова сценария !';
        echo json_encode($response);
        return;

    break;

    case 'cancel':

        if (!isset($_GET['eid']))
        {
            $response->error = 'Нет номера сценария!';
            echo json_encode($response);
            return;
        }

        $sth = $dbh->prepare('SELECT ei.*, nm.online FROM event_items ei, network_map nm WHERE nm.c_id = ei.c_id and ei.e_id=:eid');

        $sth->bindParam(':eid', intval($_GET['eid']), PDO::PARAM_INT);

        $sth->execute();

        $alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

        if (count($alldb) == 0)    
        {
            $response->error = 'Неправильный номер сценария !';
            echo json_encode($response);
            return;
        }

        $noonline = array();
        $ins_query = 'insert into cmd_queue (uid, c_id, cmd, param, user) values ';
        $comma = false;

        foreach( $alldb as $key => $val)
        {
            if ($val['online'] == 0)
            {
                array_push($noonline, $val['c_id']);
            }

            if($comma == true)
            {
                $ins_query .= ',';
            }

            $ins_query .= '(UUID(),'.$val['c_id'].',18, 0,"'.$user['login'].'")';
            $comma = true;
        }

        if (count($noonline) > 0)
        {
            $response->error = 'Нельзя отменить сценарий пока контроллер(ы):'.implode(',',$noonline).' отключены !';
            echo json_encode($response);
            return;
        }

        try
        {
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $dbh->beginTransaction();

            $dbh->exec($ins_query);

            $sth = $dbh->prepare('update events set act=0 where e_id=:eid');
            $sth->execute(array('eid'=>intval($_GET['eid'])));

            $sth = $dbh->prepare('insert into log (log_date,log_type, imp, user,log_msg) values (NOW(),0,0,:user,"Оператор отменил сценарий")');
            $sth->execute(array('user'=> $user['login']));

            $dbh->commit();

        } 
        catch (Exception $e)
        {
            $dbh->rollBack();
            $response->error = "Ошибка отмены сценария !\nПовторите еще.";
            echo json_encode($response);
            return;
        }

        $response->status = 'Выполнена команда отмены сценария!';
        echo json_encode($response);
        return;

    break;

}

?>